package com.sunk.ytmall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sunk.ytmall.common.Result;
import com.sunk.ytmall.entity.*;
import com.sunk.ytmall.entity.dto.AddCartDTO;
import com.sunk.ytmall.entity.dto.selectGoodsListDTO;
import com.sunk.ytmall.entity.vo.CartVO;
import com.sunk.ytmall.entity.vo.ProductInfoVO;
import com.sunk.ytmall.enums.CartStatusEnum;
import com.sunk.ytmall.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: Sunk 673116067@qq.com
 * @Date: 2018/4/18 14:41
 * @Description:商品接口层
 */
@RestController
@RequestMapping("/goods")
@Transactional
public class GoodsController {

    private final Logger logger= LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICommonInfoService commonInfoService;
    @Autowired
    private IShowService showService;
    @Autowired
    private ITypeService typeService;
    /**
     * 产品详情
     * @param goods
     * @return
     */
    @RequestMapping("/productDet")
    public Result getGoods(Goods goods){
        Result result=new Result(true);
        ProductInfoVO p=goodsService.getProductInfo(goods);
        result.setResult(p);
        return result;
    }
    @RequestMapping("/getGoods")
    public Result getGoodsList(selectGoodsListDTO dto){
        Result result=new Result(true);
        System.out.println(dto);
        EntityWrapper e=new EntityWrapper<Goods>();
        if(dto.getPriceGt()!=null) {
            e.gt("product_price",dto.getPriceGt());
        }
        if(dto.getPriceLte()!=null) {
            e.lt("product_price",dto.getPriceLte());
        }
        if(dto.getKey()!=null) {
            e.like("product_name",dto.getKey());
        }
        if(dto.getTypeName()!=null){
            e.eq("type_id",typeService.selectOne(new EntityWrapper<Type>().eq("type_name",dto.getTypeName())).getTypeId());
        }
        //排序规则
        switch (dto.getSort()){
            //1 默认
            case "":
                break;
            //2 价格从低到高
            case "1":
                e.orderBy("product_price",true);
                break;
            //3 价格从高到低
            case "-1":
                e.orderBy("product_price",false);
                break;
        }

        Page<Goods> list=goodsService.selectPage(
                new Page<Goods>(dto.getPage(), 8),
                e
        );
        //增加图片连接
//        commonInfoService.addUrlImgGoods(list.getRecords());
        result.setResult(list);
        return result;
    }



    @RequestMapping("/init")
    public void init(@RequestBody JSONObject params){
        List<Map> list= (List<Map>) params.get("result");
        List<Goods> insertList=new ArrayList<Goods>();
        for (Map m:list){
            Goods g=new Goods();
            g.setProductId(Long.parseLong(m.get("productId")+""));
            g.setProductName((String) m.get("productName"));
            g.setProductPrice(Long.parseLong(m.get("prodcutPrice")+""));
            g.setProductImg((String) m.get("prodcutImg"));
            insertList.add(g);
        }
        goodsService.insertBatch(insertList);
    }

    /**
     * 得到购物车内容
     * @return
     */
    @RequestMapping("/getCart")
    public Result getCart(){
        //1.获取session中的用户id
        Result result=new Result();
        //2.查询缓存中购物车信息

        //3.缓存中没有，则查数据库
        Order order=getOrder();
        List<CartVO> list=JSON.parseArray(order.getOrderList(),CartVO.class);
        for (CartVO cartVO:list){
            //根据订单中的id，加载详细数据,补全数据

            completionCarts(cartVO,goodsService.selectOne(
                    new EntityWrapper<Goods>()
                    .eq("product_id",cartVO.getProductId())
                )
            );
        }
        //增加图片地址
//        commonInfoService.addUrlImgCart(list);
        System.out.println(list);
        order.setOrderList(JSON.toJSONString(list));

        result.setResult(order.getOrderList());
        result.setSuccess(true);
        return result;
    }

    private void completionCarts(CartVO cartVO, Goods goods) {
        cartVO.setProductName(goods.getProductName());
        cartVO.setProductImg(goods.getProductImg());
        cartVO.setProductPrice(goods.getProductPrice());
    }

    /**
     * 商品加入购物车
     * @return
     */
    @RequestMapping("/addCart")
    public Result addCart(@RequestBody AddCartDTO addCartDTO){
        System.out.println(addCartDTO);
        Result result=new Result();
        Order order=getOrder();
        if(order==null){
            //新增购物车
            List list= new ArrayList();
            list.add(addCartDTO);
            order.setOrderList(JSON.toJSONString(list));
            order.setStatus(CartStatusEnum.CHOOSE.getStatus());
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            orderService.insert(order);
        }
        else if(order.getOrderList()!=null){
            Boolean f=true;
            order.setUpdateTime(new Date());
            //原有购物车追加
            List<AddCartDTO> list=JSON.parseArray(order.getOrderList(),AddCartDTO.class);

            System.out.println(list);
            if(list.size()>=0)
            for(AddCartDTO pro:list){
                if(pro.getProductId().equals(addCartDTO.getProductId())){
                    pro.setProductNum(pro.getProductNum()+addCartDTO.getProductNum());
                    f=false;
                    break;
                }
            }
            if(f){
                addCartDTO.setChecked(true);
                addCartDTO.setProductNum(1l);
                list.add(addCartDTO);
            }

            order.setOrderList(JSON.toJSONString(list));
            orderService.updateById(order);
        }
        result.setSuccess(true);

        return  result;
    }

    /**
     * 购物车
     * 可能操作：数量更改,删除,是否选中，清空
     */
    @RequestMapping("/delCart")
    public Result deleteCart(@RequestBody AddCartDTO addCartDTO){
        Result result=new Result();
        Order order=getOrder();
        System.out.println(addCartDTO);
        //数据中的订单
        List<AddCartDTO> list=JSON.parseArray(order.getOrderList(),AddCartDTO.class);
        System.out.println(list);
        for(AddCartDTO a:addCartDTO.getList()){
            System.out.println(a);
            for(AddCartDTO acd:list){
                if(acd.getProductId().equals(a.getProductId())){
                    list.remove(acd);
                    break;
                }
            }
        }

        order.setOrderList(JSON.toJSONString(list));
        orderService.updateById(order);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/cartEdit")
    public Result cartEdit(@RequestBody AddCartDTO addCartDTO){
        Result result=new Result();
        Order order=getOrder();
        //数据中的订单
        List<AddCartDTO> list=JSON.parseArray(order.getOrderList(),AddCartDTO.class);
        for(AddCartDTO acd:list){
            if(acd.getProductId().equals(addCartDTO.getProductId())){
                acd.setProductNum(addCartDTO.getProductNum());
                acd.setChecked(addCartDTO.getChecked());
                break;
            }
        }
        order.setOrderList(JSON.toJSONString(list));
        orderService.updateById(order);
        result.setSuccess(true);
        return result;
    }


    @RequestMapping("/updateCart")
    public Result updateCart(@RequestBody AddCartDTO addCartDTO){
        Result result=new Result();
        Order order=getOrder();
        //数据中的订单
        List<AddCartDTO> list=JSON.parseArray(order.getOrderList(),AddCartDTO.class);
        //判断
        switch (addCartDTO.getType()){
            case "del":
                for(AddCartDTO a:addCartDTO.getList()){
                    for(AddCartDTO acd:list){
                        if(acd.getProductId().equals(a.getProductId())){
                            list.remove(acd);
                            break;
                        }
                    }
                }

                order.setOrderList(JSON.toJSONString(list));
                orderService.updateById(order);
                break;
            //修改单个商品数量
            case "updateNum":
                for(AddCartDTO acd:list){
                    if(acd.getProductId().equals(addCartDTO.getProductId())){
                        acd.setProductNum(addCartDTO.getProductNum());
                        break;
                    }
                }
                order.setOrderList(JSON.toJSONString(list));
                orderService.updateById(order);
                break;
            //修改单个商品选中
            case "updateCheck":
                for(AddCartDTO acd:list){
                    if(acd.getProductId().equals(addCartDTO.getProductId())){
                        acd.setChecked(!acd.getChecked());
                        break;
                    }
                }
                order.setOrderList(JSON.toJSONString(list));
                orderService.updateById(order);
                break;
            //修改全部商品选中状态
            case "updateCheckAll":
                for(AddCartDTO acd:list){
                        acd.setChecked(addCartDTO.getChecked());
                }
                order.setOrderList(JSON.toJSONString(list));
                orderService.updateById(order);
                break;
        }
        //数据库

        //缓存

        result.setSuccess(true);
        return result;
    }

    /**
     * 结算
     */
    @RequestMapping("/checkOut")
    public Result checkOut(@RequestBody AddCartDTO addCartDTO){
        Result result=new Result();
        Order userorder=getOrder();
        User u=commonInfoService.getUser();
        //1.查询出用户下购物车
        List<CartVO> list=JSON.parseArray(userorder.getOrderList(),CartVO.class);
        System.out.println(list.toString());
        //2.把选中的产品加入新集合
        List<CartVO> listCheck=new ArrayList<>();
        for (CartVO dto:list) {
            if(dto.getChecked()==true){
                listCheck.add(dto);
            }
        }
        list.removeAll(listCheck);
        HashMap o=new HashMap();
        Float total=0f;
        //3.补全数据 结算的时候的物品价格 状态 名称进行保存
        for (CartVO cartVO:listCheck){
            //根据订单中的id，加载详细数据,补全数据
            completionCarts(cartVO,goodsService.selectOne(
                    new EntityWrapper<Goods>()
                            .eq("product_id",cartVO.getProductId())
                    )
            );
            total+=cartVO.getProductNum()*cartVO.getProductPrice();
        }
        o.put("order",listCheck);
        o.put("total",total);
        //删除缓存和数据库相关，修改订单状态为
        //修改购物车
        Order order=new Order();
        order.setOrderList(JSONObject.toJSONString(list));
        order.setUpdateTime(new Date());
        order.setCreateTime(new Date());
        orderService.update(order,
                new EntityWrapper<Order>()
                        .eq("user_id", u.getUserId())
                        .eq("status",CartStatusEnum.CHOOSE.getStatus())
        );
        //新加订单
        order.setStatus(CartStatusEnum.NO_PAY.getStatus());
        order.setUserId(u.getUserId());
        order.setAddressId(addCartDTO.getAddressId());
        order.setOrderList(JSONObject.toJSONString(o));
        orderService.insert(order);
        Map resultMap=new HashMap();
        resultMap.put("orderId",order.getOrderId());
        result.setResult(resultMap);
        result.setSuccess(true);
        return result;
    }

    //得到session中的用户信息,并重数据库中查询用户对应的订单
    public Order getOrder(){
        User u=commonInfoService.getUser();
        Order order=new Order();
        order.setUserId(u.getUserId());
        order.setStatus(CartStatusEnum.CHOOSE.getStatus());
        Order orderSelect=orderService.selectOne(new EntityWrapper<>(order));
        if(orderSelect==null){
          return order;
        }else{
            return orderService.selectOne(new EntityWrapper<>(order));
        }
    }

    /**
     * 首页展示
     * @return
     */
    @RequestMapping("/productHome")
    public Result productHome(){
        Result result=new Result();
//        Show ss=new Show();
//        List<Goods> goods=goodsService.selectList(new EntityWrapper<Goods>());
//        ss.setShowContent(goods);
//        Goods g=goodsService.selectOne(new EntityWrapper<Goods>().eq("product_id",1));
//        ss.setShowSmall(g);
//        List<WrapVO> ws=new ArrayList<>();
//        WrapVO w1=new WrapVO();
//        w1.setProductImg("dadas");
//        w1.setLink("saddas");
//        WrapVO w2=new WrapVO();
//        w2.setProductImg("dadas");
//        w2.setLink("saddas");
//        ws.add(w1);ws.add(w2);
//        ss.setShowWrapper(ws);
//        showService.insertShow(ss);
        Map<String,Object> map=new HashMap();
        List<Show> s=showService.selectShow();
        Page<Type> p=typeService.selectPage(
                new Page<>(0,10),
                new EntityWrapper<Type>()
                .orderBy("type_priority",true)
        );
        map.put("show",s);
        map.put("typeList",p.getRecords());
        Map typeList2=new HashMap();
        for(Type t:p.getRecords()){
            Map m=new HashMap();
            m.put(t.getTypeAlias(),goodsService.selectPage(
                    new Page<>(0,24),
                    new EntityWrapper<Goods>()
                    .eq("type_id",t.getTypeId())
            ).getRecords());
            typeList2.putAll(m);
        }
        map.put("typeList2",typeList2);
        result.setResult(map);
        result.setSuccess(true);
        return result;
    }

    /**
     * 付款
     * @param order
     * @return
     */
    @RequestMapping("/payMent")
    public Result payMent(@RequestBody Order order){
        Result result=new Result();
        //判断订单是否所属当前用户
        User u=commonInfoService.getUser();
        Order o=orderService.selectById(order.getOrderId());
        if(o.getUserId().equals(u.getUserId())){
            order.setUpdateTime(new Date());
            order.setStatus(CartStatusEnum.PAY.getStatus());
            orderService.updateById(order);
            //增加对应产品售出数量
            Map json=JSONObject.parseObject(order.getOrderList(),HashMap.class);
            List<Goods> list=JSONArray.parseArray(json.get("order").toString(),Goods.class);
            for(Goods g:list){
                goodsService.addSoldNum(g);
            }
        }else{
            result.setMessage("当前订单不存在");
            result.setSuccess(false);
            return result;
        }
        System.out.println(1231231213);
        result.setSuccess(true);
        return result;
    }


    @GetMapping("/fingGoodsByKey")
    public Result fingGoodsByKey(String key){
        Result result=new Result();
        Page<Map<String, Object>> list=null;
        if(key==null || key.trim().equals("")){
            list=goodsService.selectMapsPage(
            new Page<>(0,5),
                    new EntityWrapper<Goods>()
                    .setSqlSelect("product_name as value")
                    .orderBy("create_time",false)
            );
        }else{
            list=goodsService.selectMapsPage(
                    new Page<>(0,5),
                    new EntityWrapper<Goods>()
                            .setSqlSelect("product_name as value")
                            .like("product_name",key)
                            .orderBy("create_time",false)
            );
        }
        result.setResult(list.getRecords());
        result.setSuccess(true);
        return result;
    }
}
